package com.python.listener.core;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.python.listener.Exception.CustomException;
import com.python.listener.annotation.EnablePyServiceDiscover;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic;
import java.io.IOException;
import java.util.List;
import java.util.Set;

/**
 * 编译期调用python方法生成python服务中既有方法的class文件并写入可调用接口
 *
 * @author zt
 */
@SupportedSourceVersion(SourceVersion.RELEASE_11)
@SupportedAnnotationTypes(value = {"com.python.listener.annotation.EnablePyServiceDiscover"})
public class DiscoveryManager extends AbstractProcessor {

    private Filer filer;

    private Messager messager;

    @Override
    public synchronized void init(ProcessingEnvironment processingEnv) {
        super.init(processingEnv);
        this.filer = processingEnv.getFiler();
        this.messager = processingEnv.getMessager();
        messager.printMessage(Diagnostic.Kind.NOTE, "init");
    }

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        messager.printMessage(Diagnostic.Kind.NOTE, "process");
        Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(EnablePyServiceDiscover.class);
        boolean flag = false;
        for (Element element : elements) {
            if (flag) {
                break;
            }
            SpringBootApplication bootApplication = element.getAnnotation(SpringBootApplication.class);
            if (bootApplication == null){
                throw new CustomException("EnablePyServiceDiscover 注解必须作用于springboot启动项");
            }
            PackageElement p = (PackageElement) element.getEnclosingElement();
            messager.printMessage(Diagnostic.Kind.NOTE, element.getClass().getPackageName());
            EnablePyServiceDiscover enablePyServiceDiscover = element.getAnnotation(EnablePyServiceDiscover.class);
            ChannelSocketWrite.init(enablePyServiceDiscover.serviceAddress(), enablePyServiceDiscover.servicePort());
            String result = ChannelSocketWrite.call("func_dic_list");
            result = result.replace("'", "\"").replace("(", "[").replace(")", "]");
            messager.printMessage(Diagnostic.Kind.NOTE, result);
            List<JSONObject> funcInfos = JSON.parseArray(result, JSONObject.class);
            String filePackage = p.getQualifiedName() + ".rpc_service";
            try {
                // 生成接口的文件
                GeneFile.geneInterface(funcInfos, filePackage).writeTo(filer);
                // 只生成实现类的文件
                GeneFile.geneImpl(funcInfos, filePackage, enablePyServiceDiscover.serviceAddress(), enablePyServiceDiscover.servicePort())
                        .writeTo(filer);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                flag = true;
            }
        }
        return false;
    }

}
